package com.xms.dependency.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xms.core.exception.XmsException;
import com.xms.core.module.ModuleCollection;
import com.xms.datacore.service.UpdaterService;
import com.xms.dependency.entity.Dependency;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;

/**
 * <p>
 * DependencyUpdaterService
 * </p>
 *
 * @author migo
 * @since 2021/10/23
 */
@Service
public class DependencyUpdaterService extends UpdaterService<Dependency> implements IDependencyUpdaterService {
    private IDependencyCreaterService _dependencyCreaterService;

    @Autowired
    public DependencyUpdaterService(IDependencyCreaterService dependencyCreaterService) {
        _dependencyCreaterService = dependencyCreaterService;
    }

    @Override
    public boolean update(int dependentComponentType, UUID dependentObjectId, int requiredComponentType, Collection<UUID> requiredObjectId) throws XmsException, SQLException {
        //先删除原有的
        super.getService().remove(new LambdaQueryWrapper<Dependency>()
                .eq(Dependency::getDependentcomponenttype, dependentComponentType)
                .eq(Dependency::getDependentobjectid, dependentObjectId)
                .eq(Dependency::getRequiredcomponenttype, requiredComponentType));
        //新增
        if (CollectionUtil.notEmpty(requiredObjectId)) {
            return _dependencyCreaterService.create(dependentComponentType, dependentObjectId, requiredComponentType, requiredObjectId);
        }
        return true;
    }

    @Override
    public boolean update(String dependentComponentName, UUID dependentObjectId, String requiredComponentName, Collection<UUID> requiredObjectId) throws XmsException, SQLException {
        return this.update(ModuleCollection.getIdentity(dependentComponentName), dependentObjectId, ModuleCollection.getIdentity(requiredComponentName), requiredObjectId);
    }

    @Override
    public boolean update(int dependentComponentType, UUID dependentObjectId, int requiredComponentType, UUID requiredObjectId) throws XmsException, SQLException {
        return this.update(dependentComponentType, dependentObjectId, requiredComponentType, Arrays.asList(requiredObjectId));
    }

    @Override
    public boolean update(String dependentComponentName, UUID dependentObjectId, String requiredComponentName, UUID requiredObjectId) throws XmsException, SQLException {
        return this.update(ModuleCollection.getIdentity(dependentComponentName), dependentObjectId, ModuleCollection.getIdentity(requiredComponentName), requiredObjectId);
    }
}
